<template>
  <span
    class="pt-upload-img"
    @click="handleClick"
    :style="{
      width,
      height,
      lineHeight: height,
      cursor: readyonly ? 'default' : 'pointer'
    }"
  >
    <img v-if="img.url" :src="img.url" />
    <i v-else :style="[{
      'font-size': tipSize
    }]" class="el-icon el-icon-plus">{{ tip }}</i>
    <input ref="file" class="file" @change="handleChange" type="file" />
  </span>
</template>

<script>
import { uploadImg } from "@/api/desktop/file";
import { Message } from "element-ui";
export default {
  name: "ptUploadImg",
  props: {
    width: {
      type: String,
      default: "136px"
    },
    height: {
      type: String,
      default: "76px"
    },
    img: {
      type: Object,
      default () {
        return {
          id: "",
          url: ""
        };
      }
    },
    readyonly: {
      type: Boolean,
      default: false
    },
    tipSize: {
      type: String,
      default: "20px"
    },
    tip: {
      type: String,
      default: ""
    }
  },
  methods: {
    handleClick () {
      if (this.readyonly) {
        return;
      }
      this.$refs.file.value = "";
      this.$refs.file.click();
    },
    handleChange (ev) {
      const vm = this;
      const file = ev.target.files[0];
      uploadImg({
        file
      }).then(res => {
        let resData = res.data;
        if (resData.code === 0) {
          vm.img.id = resData.data.id;
          vm.img.url = resData.data.url;
        } else {
          Message({
            type: "error",
            message: "上传图片失败"
          });
        }
        this.$emit("uploadCallback", res);
      });
    }
  }
};
</script>

<style lang="less" scoped>
.pt-upload-img {
  display: inline-block;
  border: 1px solid #dcdfe6;
  text-align: center;
  border-radius: 4px;
  i.el-icon-plus {
    font-size: 20px;
  }
  img {
    width: 100%;
    height: 100%;
    border: none;
  }
  .file {
    display: none;
  }
}
</style>